<template>
  <div class="app-container">
    <div class="dms-app-container">
      <!-- 项目列表-》点击树进行懒加载接口 -->
      <div class="inter-left-plan">
        <el-card shadow="never">
          <div class="box-style">
            <el-tree
              :props="defaultProps"
              empty-text="暂无数据"
              lazy
              :load="loadNode"
              @node-click="handleNodeClick"
              ref="dmsTree"
              node-key="id"
              :default-expanded-keys="expandedKey"
              :highlight-current="true"
              :current-node-key="nodeKey"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <!-- 项目 -->
                <template v-if="data.type === 0">
                  <span
                    style="
                      font-size: 14px;
                      width: 7vw;
                      overflow: hidden;
                      word-break: keep-all;
                      white-space: nowrap;
                      text-overflow: ellipsis;
                    "
                    >{{ node.label }}
                  </span>
                </template>
                <!-- 接口 -->
                <template v-else>
                  <div class="dms-node-tree">
                    <div class="dms-node-right">
                      <span
                        style="
                          max-width: 120px;
                          min-width: 50px;
                          overflow: hidden;
                          word-break: keep-all;
                          white-space: nowrap;
                          text-overflow: ellipsis;
                          color: gray;
                        "
                      >
                        {{ node.label }}
                      </span>
                    </div>
                  </div>
                </template>
              </span>
            </el-tree>
          </div>
        </el-card>
      </div>
      <!-- 接口详细信息，可编辑修改 -->
      <div class="inter-right-plan" v-if="showRightContent">
        <div class="inter-list-table">
          <div class="inter-execute-button">
            <el-popover
              placement="top-start"
              title="说明"
              trigger="hover"
              width="200"
              content="如果未选择计划，则默认执行全部计划。"
              style="float: right"
            >
              <el-button
                type="primary"
                slot="reference"
                @click="executePlan"
                v-preventReClick
              >
                执行计划
              </el-button>
            </el-popover>
          </div>
          <el-table
            :data="planInterData"
            v-loading="loading"
            height="70vh"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column
              label="接口ID"
              prop="interId"
              width="70"
            ></el-table-column>
            <el-table-column
              label="接口名称"
              prop="interName"
              align="center"
              show-overflow-tooltip
            ></el-table-column>
          </el-table>
        </div>
        <div class="inter-result-table">
          <el-empty v-if="showExecuteRes" description="暂无计划执行">
          </el-empty>
          <div v-else>
            <div style="width: 100%; display: flex; justify-content: flex-end">
              <el-button type="primary" @click="clearRes"> 清空结果 </el-button>
            </div>
            <el-divider></el-divider>
            <div style="height: 70vh; overflow: auto">
              <el-timeline>
                <el-timeline-item
                  v-for="(activity, index) in activities"
                  :key="index"
                  :icon="activity.icon"
                  :type="activity.type"
                  :color="activity.color"
                  :size="activity.size"
                  :timestamp="activity.timestamp"
                >
                  <span>
                    <span style="font-size: 20px">{{ activity.content }}</span>
                    <span style="float: right">
                      <el-popover placement="left-start" trigger="click">
                        <pre>{{ activity.returnRes }}</pre>
                        <el-link
                          :underline="false"
                          :type="activity.type"
                          slot="reference"
                        >
                          查看返回结果
                        </el-link>
                      </el-popover>
                    </span>
                  </span>
                  <template v-if="activity.type === 'success'">
                    <br />
                    <span style="color: gray; font-size: 14px"
                      >响应时间: {{ activity.time }}ms</span
                    >
                  </template>
                </el-timeline-item>
              </el-timeline>
            </div>
          </div>
        </div>
      </div>
      <div class="empty-content" v-else>
        <img src="@/assets/images/empty.png" />
        <span style="font-size: 20px; color: #909399">请选择测试计划</span>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapState } from "vuex";
import { listPlanInter } from "@/api/dmsIms/planinter";
import { executeInterface } from "@/api/dmsIms/interface";
import { listPlan } from "@/api/dmsIms/plan";
import {
  interListGlobalvar,
  updateGlobalvar,
  getGlobalvarbyName,
} from "@/api/dmsIms/globalvar";
// import RequestData from "./requestData";

export default {
  name: "PlanExecute",
  mounted() {},
  computed: {
    ...mapState({
      simpleProList: (state) => state.prolist.simpleProList,
    }),
  },
  data() {
    return {
      // treeData: [],
      id: "",
      expandedKey: [],
      defaultProps: {
        children: "children",
        label: "label",
        type: "type",
        id: "id",
        isLeaf: "leaf",
      },
      showRightContent: false,
      loading: true,
      node_had: [],
      resolve_had: "",
      currData: {},
      currNode: {},
      nodeKey: "",
      queryParams: {
        pageNum: 1,
        pageSize: 1000,
        planName: null,
        planCode: null,
        planOfpro: null,
      },
      planInterData: [],
      multipleSelection: [],
      showExecuteRes: true,
      activities: [],
    };
  },
  methods: {
    // vuex中的actions方法简写方式
    ...mapActions(["getProList"]),
    loadNode(node, resolve) {
      if (node.level === 0) {
        this.node_had = node; //这里是关键！在data里面定义一个变量，将node.level == 0的node存起来
        this.resolve_had = resolve; //同上，把node.level == 0的resolve也存起来
        this.node_had.childNodes = [];
        return this.getFirstNode(node, resolve);
      }
      if (node.level === 1) {
        return this.getChildrenNode(node, resolve);
      }
      if (node.level > 1) {
        return resolve([]);
      }
    },
    getFirstNode(node, resolve) {
      this.getProList()
        .then(() => {
          let treeData = [];
          for (let index = 0; index < this.simpleProList.length; index++) {
            treeData.push({
              id: this.simpleProList[index].id,
              label: this.simpleProList[index].proName,
              type: 0,
              leaf: false,
              children: [],
            });
          }
          return treeData;
        })
        .then((res) => {
          resolve(res);
        });
    },
    getChildrenNode(node, resolve) {
      let proId = node.data.id;
      let returnData = [];
      // this.nodeTreeData = [];
      this.queryParams.planOfpro = proId;
      listPlan(this.queryParams)
        .then((response) => {
          response.rows.forEach((elem) => {
            returnData.push({
              id: elem.id,
              label: elem.planName,
              type: 1,
              leaf: true,
            });
          });
          return returnData;
        })
        .then((res) => {
          resolve(res);
        });
    },
    handleNodeClick(data, node) {
      this.currNode = node;
      // 加载计划中的接口
      if (data.type === 1) {
        this.loading = true;
        this.planInterData = [];
        this.showRightContent = true;
        this.showExecuteRes = true;
        this.activities = [];
        // console.log(data);
        listPlanInter(data.id)
          .then((response) => {
            this.planInterData = response.rows;
          })
          .then((_) => {
            this.loading = false;
          });
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    clearRes() {
      this.activities = [];
    },
    async executePlan() {
      this.showExecuteRes = false;
      this.activities = [];
      if (this.multipleSelection.length === 0) {
        //执行全部计划
        for (let index = 0; index < this.planInterData.length; index++) {
          const elem = this.planInterData[index];
          await executeInterface(elem.interId)
            .then((response) => {
              if (response.data.hasOwnProperty("errorMsg")) {
                this.activities.push({
                  content: elem.interName,
                  size: "large",
                  type: "danger",
                  returnRes: response.data.errorMsg,
                });
              } else {
                this.activities.push({
                  content: elem.interName,
                  size: "large",
                  type: "success",
                  time: response.data.ResponseTime,
                  returnRes: JSON.stringify(
                    JSON.parse(response.data.ResponseData),
                    null,
                    2
                  ),
                });
                return response.data.ResponseData;
              }
            })
            .then(async (dmsRes) => {
              if (dmsRes) {
                // 在变量表中，找到接口id对应的变量，正则匹配变量值然后修改
                await interListGlobalvar(elem.interId).then((response) => {
                  response.rows.forEach((element) => {
                    if (
                      element.varType === 3 &&
                      element.varRules !== "" &&
                      element.varRules !== null
                    ) {
                      let dmsRule = new RegExp(element.varRules);
                      let res = dmsRule.exec(dmsRes);
                      if (res !== null) {
                        if (res.length === 1) {
                          element.varValue = res[0];
                        } else if (res.length === 2) {
                          element.varValue = res[1];
                        }
                      }
                      updateGlobalvar(element);
                    }
                  });
                });
              }
            });
        }
      } else {
        //执行选中的计划
        for (let index = 0; index < this.multipleSelection.length; index++) {
          const elem = this.multipleSelection[index];
          await executeInterface(elem.interId)
            .then((response) => {
              if (response.data.hasOwnProperty("errorMsg")) {
                this.activities.push({
                  content: elem.interName,
                  size: "large",
                  type: "danger",
                });
              } else {
                this.activities.push({
                  content: elem.interName,
                  size: "large",
                  type: "success",
                  time: response.data.ResponseTime,
                  returnRes: JSON.stringify(
                    JSON.parse(response.data.ResponseData),
                    null,
                    2
                  ),
                });
                return response.data.ResponseData;
              }
            })
            .then((dmsRes) => {
              if (dmsRes) {
                // 在变量表中，找到接口id对应的变量，正则匹配变量值然后修改
                interListGlobalvar(elem.interId).then((response) => {
                  response.rows.forEach((element) => {
                    if (
                      element.varType === 3 &&
                      element.varRules !== "" &&
                      element.varRules !== null
                    ) {
                      let dmsRule = new RegExp(element.varRules);
                      let res = dmsRule.exec(dmsRes);
                      if (res !== null) {
                        if (res.length === 1) {
                          element.varValue = res[0];
                        } else if (res.length === 2) {
                          element.varValue = res[1];
                        }
                      }
                      updateGlobalvar(element);
                    }
                  });
                });
              }
            });
        }
      }
    },
  },
};
</script>

<style scope>
.inter-left-plan {
  width: 15vw;
  height: 80vh;
  margin-right: 20px;
}
.inter-right-plan {
  width: 60vw;
  height: 80vh;
  display: flex;
}
.box-style {
  height: 80vh;
  overflow: auto;
}
.custom-tree-node {
  display: flex;
  flex-grow: 1;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  color: black;
}
/* 改变被点击节点背景颜色，字体颜色 */
.el-tree-node:focus > .el-tree-node__content {
  background-color: rgb(237, 237, 237) !important;
  color: #fff !important;
}
/*节点失焦时的背景颜色*/
.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #4a9de7 !important;
  color: #fff !important;
}
.el-select .el-input {
  width: 130px;
}
.input-with-select {
  background-color: rgb(242, 242, 242);
}
.dms-app-container {
  display: flex;
}
.dms-node-tree {
  display: flex;
  align-items: center;
  justify-content: center;
}
.dms-node-left {
  width: 40px;
  margin-right: 2px;
  /* text-align: right; */
  font-size: 10px;
  margin-top: 2px;
}
.dms-node-right {
  display: flex;
}
.dms-input {
  display: flex;
  margin-bottom: 20px;
}
.empty-content {
  display: flex;
  flex-direction: column;
  width: 60vw;
  height: 80vh;
  justify-content: center;
  align-items: center;
}
.inter-list-table {
  width: 28vw;
  margin-right: 20px;
  overflow: auto;
}
.inter-result-table {
  width: 28vw;
  height: 80vh;
}
</style>
